import audioop
import base64
import os

import requests
def call_transfer_api(title:str, speech: bytes, from_user: str, to_user:str):
    url = "http://127.0.0.1:37090/open/asr/offline"
    headers = {
        "Authorization": "Access=13"
    }
    myParams = {"itn": True, "fs": 8000, "wav": base64.b64encode(speech), 'title': title, 'format': 'pcm16bit', 'fromUser':from_user, 'toUser':to_user}
    res = requests.post(url=url,headers=headers, json=myParams)

    print("response:", res.text)  # 返回请求结果
def walk_wave_from_folder(parent_path: str):
    print(parent_path)
    files = os.listdir(parent_path)
    for file in files:
        if file.startswith('.'):
            continue
        file_path = os.path.join('{0}/'.format(parent_path), file)
        if os.path.isdir(file_path):
            walk_wave_from_folder(parent_path=file_path)
        elif file_path.endswith('.wav'):
            print(file_path)
            with open(file_path, "rb") as f:
                wav_data = f.read()
                f.close()

                title = file.replace('.wav', '')
                names = title.split('_')
                from_user = ''
                to_user = ''
                if len(names) > 1:
                    from_user = names[1]
                if len(names) > 2:
                    to_user = names[2]
                #print(f'title={title} from_user:{from_user} to_user:{to_user}')
                call_transfer_api(title=f'{title}', speech=wav_data, from_user=from_user, to_user=to_user)


def walk_wave_datas():
    root_path = '/home/leo/Documents/北京地铁/调度录音/新建文件夹'
    walk_wave_from_folder(parent_path=root_path)
    '''
    root_files = os.listdir(root_path)
    for file in root_files:
        if file.startswith('.'):
            continue
        if os.path.isdir(file):

        parent_path = os.path.join('{0}/'.format(root_path), parent)
        wav_folder = os.listdir(parent_path)
        for wav in wav_folder:
            if wav.startswith('.'):
                continue
            wav_path = os.path.join('{0}/'.format(parent_path), wav)
            with open(wav_path, "rb") as f:
                wav_data = f.read()
                f.close()

                title = wav.replace('AutoExt-', '').replace('.wav', '')
                names = title.split('-')
                from_user = names[6]
                to_user = names[7]

                call_transfer_api(title=f'{parent}-{title}', speech=wav_data, from_user=from_user,to_user=to_user)
    '''

walk_wave_datas()